package com.hudson.core.util;


import com.hudson.common.domain.meta.MsgIdInfo;

import java.nio.ByteBuffer;

public class MsgIdUtil {

    // 二进制转为十六进制字符串，大小翻倍
    public static final int MSG_LENGTH = (4 + 4 + 8 + 4) * 2;
    private static final char[] hexChars = "0123456789ABCDEF".toCharArray();

    public static String encode(String address, int port, long offset, int size) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(4 + 4 + 8 + 4);
        byteBuffer.put(ipv4ToBytes(address));

        byteBuffer.putInt(port);
        byteBuffer.putLong(offset);
        byteBuffer.putInt(size);

        return bytesToHex(byteBuffer.array());
    }

    public static byte[] ipv4ToBytes(String ipv4) {
        String[] parts = ipv4.split("\\.");
        if (parts.length != 4) {
            throw new IllegalArgumentException("无效的ipv4地址：" + ipv4);
        }
        byte[] bytes = new byte[4];
        for (int i = 0; i < parts.length; i++) {
            int partInt = Integer.parseInt(parts[i]);
            if (partInt < 0 || partInt > 255) {
                throw new IllegalArgumentException();
            }
            bytes[i] = (byte) partInt;
        }
        return bytes;
    }

    public static String bytesToHex(byte[] bytes) {
        char[] chars = new char[bytes.length * 2];
        for (int i = 0; i < bytes.length; i++) {
            int val = bytes[i] & 0xFF;
            chars[i * 2] = hexChars[(val >>> 4)];
            chars[i * 2 + 1] = hexChars[val & 0x0F];
        }
        return new String(chars);
    }


    // 解码：16进制字符串 → IPv4(String) + int + int + long
    public static MsgIdInfo decode(String hexStr) {
        // 1. 16进制字符串转回字节数组
        byte[] bytes = hexToBytes(hexStr);
        ByteBuffer buffer = ByteBuffer.wrap(bytes);

        // 2. 读取数据（按编码顺序）
        byte[] ipv4Bytes = new byte[4];
        buffer.get(ipv4Bytes);       // 读取IPv4的4字节
        String ipv4 = bytesToIPv4(ipv4Bytes); // 转回IPv4字符串

        int port = buffer.getInt();  // 读取第一个int
        long offset = buffer.getLong();// 读取long
        int size = buffer.getInt();  // 读取第二个int

        return new MsgIdInfo(ipv4, port, offset, size);
    }


    // 4字节转IPv4字符串（如 [0xC0, 0xA8, 0x01, 0x01] → "192.168.1.1"）
    private static String bytesToIPv4(byte[] bytes) {
        if (bytes.length != 4) {
            throw new IllegalArgumentException("无效的IPv4字节数组");
        }
        // 转为无符号整数（避免负数，如0xFF → 255而非-1）
        return String.format("%d.%d.%d.%d",
                bytes[0] & 0xFF,
                bytes[1] & 0xFF,
                bytes[2] & 0xFF,
                bytes[3] & 0xFF);
    }

    // 16进制字符串转字节数组
    private static byte[] hexToBytes(String hexStr) {
        int len = hexStr.length();
        byte[] bytes = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            bytes[i / 2] = (byte) ((Character.digit(hexStr.charAt(i), 16) << 4)
                    + Character.digit(hexStr.charAt(i + 1), 16));
        }
        return bytes;
    }
}